package com.yunshipei.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.adapter.DepartmentNameAdapter;
import com.yunshipei.adapter.MyListViewAdapter;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.YspEvent.DepartmentBackModelEvent;
import com.yunshipei.ui.fragment.DepartmentFragment;

import java.util.ArrayList;

import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;

public class DepartmentActivity extends BaseActivity implements DepartmentNameAdapter.OnItemClickListener, View.OnClickListener, MyListViewAdapter.OnDepartmentPathForwardListener {
    public static final String DEPARTMENT_NAME_LSIT = "department_name_list";

    private DepartmentFragment mDepartmentFragment;
    private SharedPreferences mySharedPreferences = null;
    private LinearLayout mTitleBar;
    private Dialog mDialog;
    private String departId, parentName, companyId, uuid;
    private RecyclerView recyclerView;
    private LinearLayoutManager manager;
    private ArrayList<String> list;
    private DepartmentNameAdapter adapter;
    private LinearLayout rootView;
    private TextView mTextView;
    //用来一次关闭多个activity用
    private int tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_department);
        EventBus.getDefault().register(this);
        mySharedPreferences = getApplication().getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        companyId = mySharedPreferences.getString("companyId", "");
        uuid = mySharedPreferences.getString("uuid", "");
        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        final String name = b.getString("departName");
        departId = b.getString("departId");
        parentName = b.getString("parentDepartName");
        list = b.getStringArrayList(DEPARTMENT_NAME_LSIT);
        if (list == null) {
            list = new ArrayList<>();
        }
        mDepartmentFragment = DepartmentFragment.newInstances(false);
        getSupportFragmentManager().beginTransaction().replace(R.id.container, mDepartmentFragment).commit();
        mDepartmentFragment.setDepartmentId(departId, companyId, name);
        mTitleBar = (LinearLayout) findViewById(R.id.title_bar);
        mTitleBar.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        mTextView = (TextView) findViewById(R.id.department_name);
        mTextView.setText(StringUtilSub.getInstance().SubStringAddCH(0, name, 5));
        findViewById(R.id.department_back).setOnClickListener(this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        rootView = (LinearLayout) findViewById(R.id.rootview);
        manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        list.add(StringUtilSub.getInstance().SubStringAddCH(0, parentName, 5));
        adapter = new DepartmentNameAdapter(list);
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        scrollRecyclerView2Bottom();
        tag = list.size();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.department_back:
                titlebarBackPress();
                break;
        }
    }

    @Override
    protected void onResume() {
        mDepartmentFragment.getAdapter().setOnDepartmentPathForwardListener(this);
        super.onResume();
    }

    @Override
    public void onDepartmentPathForward(Intent intent) {
        intent.putExtra(DEPARTMENT_NAME_LSIT, list);
    }

    /**
     * LoadingDialog
     *
     * @param mContext
     * @param layout
     */
    public void showRoundProcessDialog(Context mContext, int layout) {
        DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                }
                return false;
            }
        };
        mDialog = new AlertDialog.Builder(mContext).create();
        mDialog.setOnKeyListener(keyListener);
        mDialog.show();
        View view = LayoutInflater.from(mContext).inflate(layout, null);
        mDialog.getWindow().setContentView(view);
    }

    public void closeProcessDialog() {
        mDialog.dismiss();
    }

    private void showToast(String toastContext) {
        Toast.makeText(DepartmentActivity.this, toastContext, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back2Main();
        }
        return false;
    }

    private void scrollRecyclerView2Bottom() {
        ViewTreeObserver observer = rootView.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                rootView.getViewTreeObserver().removeOnPreDrawListener(this);
                if (list.size() != 0 && !list.isEmpty()) {
                    recyclerView.smoothScrollToPosition(list.size() - 1);
                }
                return true;
            }
        });
    }

    //后退一步
    private void titlebarBackPress() {
        if (list.size() != 0 && !list.isEmpty()) {
            list.remove(list.size() - 1);
            finish();
        }
    }

    //后退到mainactivity
    private void back2Main() {
        list.clear();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onItemClick(View view, int position) {
        for (int i = list.size() - 1; i >= position; i--) {
            list.remove(i);
        }
        EventBus.getDefault().post(new DepartmentBackModelEvent(position));
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void onEventMainThread(DepartmentBackModelEvent event) {
        if (this.tag > event.getTag()) {
            this.finish();
        }
    }
}
